<?php
class V_Router
{
	public $config;	
	public $routes 			= array();
	public $errorRoutes		= array();
	public $className		= '';
	public $method			= 'index';
	public $dirName			= '';
	public $uri_protocol 	= 'auto';
	public $defaultController;
	
	public function __construct()
	{
		require_once 'V/URI.php';
		require_once 'V/Config.php';
		$this->URI = new V_URI();
		$this->CONF = new V_CONFIG();
		$this->_setRouting();
	}
	
		/**
	 * Set the route mapping
	 *
	 * This function determines what should be served based on the URI request,
	 * as well as any "routes" that have been set in the routing config file.
	 *
	 * @access	private
	 * @return	void
	 */
	private  function _setRouting()
	{
		// Are query strings enabled in the config file?
		// If so, we're done since segment based URIs are not used with query strings.
		if ($this->CONF->item('enable_query_strings') === TRUE AND isset($_GET[$this->CONF->item('controller_trigger')]))
		{
			$this->setClass(trim($this->URI->filterUri($_GET[$this->CONF->item('controller_trigger')])));

			if (isset($_GET[$this->CONF->item('function_trigger')]))
			{
				$this->setMethod(trim($this->URI->filterUri($_GET[$this->CONF->item('function_trigger')])));
			}
			
			return;
		}
		
		// Load the routes.php file.
		@include(VPATH_MYAPP.DS.'config'.DS.'routes.php');
		
		$this->routes  = ( ! isset($ROUTE) OR ! is_array($ROUTE)) ? array() : $ROUTE;

		unset($ROUTE);

		// Set the default controller so we can display it in the event
		// the URI doesn't correlated to a valid controller.
		$this->defaultController = ( ! isset($this->routes['defaultController']) OR $this->routes['defaultController'] == '') ? FALSE : strtolower($this->routes['defaultController']);	
		
		// Fetch the complete URI string
		$this->URI->fetchUriString();
	
		// Is there a URI string? If not, the default controller specified in the "routes" file will be shown.
		if ($this->URI->getUriString() == '')
		{
			if ($this->defaultController === FALSE)
			{
				die("Unable to determine what should be displayed. A default route has not been specified in the routing file.");
			}
			
			if (strpos($this->defaultController, '/') !== FALSE)
			{
				$x = explode('/', $this->defaultController);

				$this->setClass(end($x));
				$this->setMethod('index');
				$this->_setRequest($x);
			}
			else
			{
				$this->setClass($this->defaultController);
				$this->setMethod('index');
				$this->_setRequest(array($this->defaultController, 'index'));
			}

			// re-index the routed segments array so it starts with 1 rather than 0
			$this->URI->reindexSegments();
			
			//log_message('debug', "No URI present. Default controller set.");
			return;
		}
		unset($this->routes['defaultController']);
		
		// Do we need to remove the URL suffix?
		$this->URI->removeUrlSuffix();
		
		// Compile the segments into an array
		$this->URI->explodeSegments();
		
		// Parse any custom routing that may exist
		$this->_parseRoutes();		
		
		// Re-index the segment array so that it starts with 1 rather than 0
		$this->URI->reindexSegments();
	}
	
	/**
	 * Set the Route
	 *
	 * This function takes an array of URI segments as
	 * input, and sets the current class/method
	 *
	 * @access	private
	 * @param	array
	 * @param	bool
	 * @return	void
	 */
	private  function _setRequest($segments = array())
	{
		$segments = $this->_validateRequest($segments);
	
		if (count($segments) == 0)
		{
			return;
		}
						
		$this->setClass($segments[0]);
		
		if (isset($segments[1]))
		{
			$this->setMethod($segments[1]);
		}
		else
		{
			// This lets the "routed" segment array identify that the default
			// index method is being used.
			$segments[1] = 'index';
		}
		
		// Update our "routed" segment array to contain the segments.
		// Note: If there is no custom routing, this array will be
		// identical to $this->URI->rsegments
		$this->URI->setRsegments($segments);
	}
	
	// --------------------------------------------------------------------
	
	/**
	 * Validates the supplied segments.  Attempts to determine the path to
	 * the controller.
	 *
	 * @access	private
	 * @param	array
	 * @return	array
	 */	
	private  function _validateRequest($segments)
	{
		$path = VPATH_MYAPP.DS.'controllers'.DS.$this->fetchDirectory().$segments[0];

		// Does the requested controller exist in the root folder?
		if (file_exists($path.'.php'))
		{
			return $segments;
		}

		// Is the controller in a sub-folder?
		if (is_dir($path))
		{		
			// Set the directory and remove it from the segment array
			$this->setDirectory($segments[0]);
			$segments = array_slice($segments, 1);
			
			if (count($segments) > 0)
			{
				// Does the requested controller exist in the sub-folder?
				
				if ( ! file_exists($path.'.php'))
				{
					die($this->fetchDirectory().$segments[0]);
				}
			}
			else
			{
				$this->setClass($this->defaultController);
				$this->setMethod('index');
			
				// Does the default controller exist in the sub-folder?
				$conFile = VPATH_MYAPP.'controllers/'.$this->fetchDirectory().$this->defaultController.'.php';
				if ( ! file_exists($conFile))
				{
					$this->clearDirectory();
					return array();
				}
			
			}

			return $segments;
		}

		// Can't find the requested controller...
		die('Can\'t find the requested "'.$segments[0].'" controller ');
	}
	
	/**
	 *  Parse Routes
	 *
	 * This function matches any routes that may exist in
	 * the config/routes.php file against the URI to
	 * determine if the class/method need to be remapped.
	 *
	 * @access	private
	 * @return	void
	 */
	private  function _parseRoutes()
	{
		// Do we even have any custom routing to deal with?
		// There is a default scaffolding trigger, so we'll look just for 1
		if (count($this->routes) == 1)
		{
			$this->_setRequest($this->URI->getSegments());
			return;
		}

		// Turn the segment array into a URI string
		$uri = implode('/', $this->URI->getSegments());

		// Is there a literal match?  If so we're done
		if (isset($this->routes[$uri]))
		{
			$this->_setRequest(explode('/', $this->routes[$uri]));		
			return;
		}
				
		// Loop through the route array looking for wild-cards
		foreach ($this->routes as $key => $val)
		{						
			// Convert wild-cards to RegEx
			$key = str_replace(':any', '.+', str_replace(':num', '[0-9]+', $key));
			
			// Does the RegEx match?
			if (preg_match('#^'.$key.'$#', $uri))
			{			
				// Do we have a back-reference?
				if (strpos($val, '$') !== FALSE AND strpos($key, '(') !== FALSE)
				{
					$val = preg_replace('#^'.$key.'$#', $val, $uri);
				}
			
				$this->_setRequest(explode('/', $val));		
				return;
			}
		}

		// If we got this far it means we didn't encounter a
		// matching route so we'll set the site default route
		$this->_setRequest($this->URI->getSegments());
	}
	
	/**
	 * Set the class name
	 *
	 * @access	public
	 * @param	string
	 * @return	void
	 */	
	public  function setClass($class)
	{
		$this->className = $class;
	}
	
		/**
	 * Fetch the current class
	 *
	 * @access	public
	 * @return	string
	 */	
	public  function fetchClass()
	{
		return $this->className;
	}
	
	// --------------------------------------------------------------------
	
	/**
	 *  Set the method name
	 *
	 * @access	public
	 * @param	string
	 * @return	void
	 */	
	public  function setMethod($method)
	{
		$this->method = $method;
	}

	// --------------------------------------------------------------------
	
	/**
	 *  Fetch the current method
	 *
	 * @access	public
	 * @return	string
	 */	
	public  function fetchMethod()
	{
		if ($this->method == $this->fetchClass())
		{
			return 'index';
		}

		return $this->method;
	}
	
	/**
	 *  Set the directory name
	 *
	 * @access	public
	 * @param	string
	 * @return	void
	 */	
	public function setDirectory($dir)
	{
		$this->dirName = $dir.'/';
	}
	
	public function clearDirectory()
	{
		$this->dirName = '';
	}

	/**
	 *  Fetch the sub-directory (if any) that contains the requested controller class
	 *
	 * @access	public
	 * @return	string
	 */	
	public function fetchDirectory()
	{
		return $this->dirName;
	}
}